class Solution
{
public:
    bool isHappy(int n)
    {
        unordered_set<int> visited{n};
        while (true)
        {
            n = digitSquareSum(n);
            if (n == 1)
            {
                return true;
            }
            if (visited.count(n))
            {
                break;
            }
            visited.insert(n);
        }
        return false;
    }

    int digitSquareSum(int n)
    {
        int result = 0;
        while (n)
        {
            int digit = n % 10;
            result += digit * digit;
            n /= 10;
        }
        return result;
    }
};